#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
通信管理器
负责串口和TCP通信的管理
"""

import os
import sys
import logging
import threading
import time
from datetime import datetime
from typing import Optional, Callable
from PyQt6.QtCore import QThread, pyqtSignal

# 串口模块已移除
SERIAL_AVAILABLE = False

try:
    from src.protocols.tcp.tcp_protocol import TCPClient, TCPCommunicationThread
    from src.protocols.tcp.tcp_server import TCPServer
    TCP_AVAILABLE = True
except ImportError as e:
    logging.warning(f"导入TCP模块失败: {e}")
    TCP_AVAILABLE = False

# 使用绝对导入，避免相对导入问题
try:
    from src.models.models import CommunicationType, ProtocolType
    from src.utils.logger_manager import get_system_logger, OperationType
except ImportError:
    # 如果绝对导入失败，尝试相对导入
    try:
        from ..models.models import CommunicationType, ProtocolType
        from ..utils.logger_manager import get_system_logger, OperationType
    except ImportError:
        # 如果都失败，使用字符串导入（延迟导入）
        CommunicationType = ProtocolType = None
        get_system_logger = None
        OperationType = None

logger = logging.getLogger(__name__)

class CommunicationManager:
    """通信管理器"""
    
    def __init__(self, db_manager=None):
        self.serial_port = None
        self.tcp_client = None
        self.tcp_server = None
        self.is_connected = False
        self.data_callback = None
        self.comm_thread = None
        self.message_count = 0
        self.db_manager = db_manager
        self.communication_type = CommunicationType.SERIAL if CommunicationType else "串口"
        
        # 系统日志管理器
        self.system_logger = get_system_logger() if get_system_logger else None
        
        # TCP服务器相关
        self.tcp_server_enabled = False
        self.tcp_server_host = "0.0.0.0"
        self.tcp_server_port = 5000
        self.tcp_server_max_clients = 10
        
        # 加载TCP服务器配置
        self._load_tcp_server_config()
        
        # 记录系统启动日志
        if self.system_logger:
            self.system_logger.log_system_event(
                "通信管理器初始化",
                "通信管理器已初始化完成",
                details={"communication_type": self.communication_type}
            )
    
    def _load_tcp_server_config(self):
        """加载TCP服务器配置"""
        try:
            if self.db_manager:
                self.tcp_server_enabled = self.db_manager.get_system_config("tcp_server_enabled") == "true"
                self.tcp_server_host = self.db_manager.get_system_config("tcp_server_host") or "0.0.0.0"
                self.tcp_server_port = int(self.db_manager.get_system_config("tcp_server_port") or "5000")
                self.tcp_server_max_clients = int(self.db_manager.get_system_config("tcp_server_max_clients") or "10")
        except Exception as e:
            logger.error(f"加载TCP服务器配置失败: {e}")
    
    def setup_serial_port(self, port: str = None, baudrate: int = None, data_bits: int = 8, 
                         stop_bits: int = 1, parity: str = 'N'):
        """设置串口"""
        if not SERIAL_AVAILABLE:
            logger.error("串口模块不可用")
            return False
        
        try:
            # 如果没有提供端口和波特率，尝试从数据库加载
            if port is None or baudrate is None:
                if self.db_manager:
                    port = port or self.db_manager.get_system_config("serial_port") or "COM3"
                    baudrate = baudrate or int(self.db_manager.get_system_config("baudrate") or "115200")
                else:
                    port = port or "COM3"
                    baudrate = baudrate or 115200
            
            logger.warning("串口功能已移除，请使用TCP通信")
            return False
        except Exception as e:
            logger.error(f"设置串口失败: {e}")
            return False
    
    def setup_tcp_client(self, host: str = None, port: int = None):
        """设置TCP客户端"""
        if not TCP_AVAILABLE:
            logger.error("TCP模块不可用")
            return False
        
        try:
            # 如果没有提供主机和端口，尝试从数据库加载
            if host is None or port is None:
                if self.db_manager:
                    host = host or self.db_manager.get_system_config("tcp_host") or "127.0.0.1"
                    port = port or int(self.db_manager.get_system_config("tcp_port") or "5000")
                else:
                    host = host or "127.0.0.1"
                    port = port or 5000
            
            self.tcp_client = TCPClient(host, port)
            self.communication_type = "TCP"
            logger.info(f"TCP客户端已设置: {host}:{port}")
            return True
        except Exception as e:
            logger.error(f"设置TCP客户端失败: {e}")
            return False
    
    def setup_tcp_server(self, host: str = None, port: int = None, max_clients: int = None):
        """设置TCP服务器"""
        if not TCP_AVAILABLE:
            logger.error("TCP模块不可用")
            return False
        
        try:
            # 如果没有提供参数，使用配置值
            host = host or self.tcp_server_host
            port = port or self.tcp_server_port
            max_clients = max_clients or self.tcp_server_max_clients
            
            self.tcp_server = TCPServer(host, port, max_clients)
            logger.info(f"TCP服务器已设置: {host}:{port}, 最大客户端数: {max_clients}")
            return True
        except Exception as e:
            logger.error(f"设置TCP服务器失败: {e}")
            return False
    
    def start_tcp_server(self) -> bool:
        """启动TCP服务器"""
        try:
            if not self.tcp_server:
                if not self.setup_tcp_server():
                    return False
            
            if self.tcp_server.is_server_running():
                logger.warning("TCP服务器已在运行")
                return True
            
            # 设置回调函数
            self.tcp_server.set_callbacks(
                on_client_connected=self._on_tcp_client_connected,
                on_client_disconnected=self._on_tcp_client_disconnected,
                on_data_received=self._on_tcp_data_received
            )
            
            success = self.tcp_server.start()
            if success:
                logger.info("TCP服务器启动成功")
            return success
            
        except Exception as e:
            logger.error(f"启动TCP服务器失败: {e}")
            return False
    
    def stop_tcp_server(self):
        """停止TCP服务器"""
        try:
            if self.tcp_server:
                self.tcp_server.stop()
                logger.info("TCP服务器已停止")
        except Exception as e:
            logger.error(f"停止TCP服务器失败: {e}")
    
    def is_tcp_server_running(self) -> bool:
        """检查TCP服务器是否运行"""
        return self.tcp_server and self.tcp_server.is_server_running()
    
    def get_tcp_server_client_count(self) -> int:
        """获取TCP服务器客户端数量"""
        if self.tcp_server:
            return self.tcp_server.get_client_count()
        return 0
    
    def get_tcp_server_client_list(self) -> list:
        """获取TCP服务器客户端列表"""
        if self.tcp_server:
            return self.tcp_server.get_client_list()
        return []
    
    def _on_tcp_client_connected(self, client_id: str):
        """TCP客户端连接回调"""
        logger.info(f"TCP客户端连接: {client_id}")
        
        # 记录通信事件日志
        if self.system_logger:
            self.system_logger.log_communication_event(
                OperationType.COMMUNICATION_CONNECT.value,
                f"TCP客户端 {client_id} 连接成功",
                connection_info={"client_id": client_id, "type": "TCP"},
                success=True
            )
    
    def _on_tcp_client_disconnected(self, client_id: str):
        """TCP客户端断开回调"""
        logger.info(f"TCP客户端断开: {client_id}")
        
        # 记录通信事件日志
        if self.system_logger:
            self.system_logger.log_communication_event(
                OperationType.COMMUNICATION_DISCONNECT.value,
                f"TCP客户端 {client_id} 断开连接",
                connection_info={"client_id": client_id, "type": "TCP"},
                success=True
            )
    
    def _on_tcp_data_received(self, client_id: str, data: bytes):
        """TCP数据接收回调"""
        data_size = len(data)
        logger.debug(f"从TCP客户端 {client_id} 接收数据: {data_size} 字节")
        
        # 记录数据接收日志
        if self.system_logger:
            try:
                # 尝试解析数据内容
                data_content = data.decode('utf-8', errors='ignore')[:100]
                self.system_logger.log_data_reception(
                    "TCP数据",
                    data_content,
                    source=f"TCP客户端 {client_id}",
                    raw_data=data.hex()[:200],  # 限制原始数据长度
                    details={
                        "client_id": client_id,
                        "data_size": data_size,
                        "protocol": "TCP"
                    }
                )
            except Exception as e:
                logger.error(f"记录TCP数据接收日志失败: {e}")
        
        # 可以在这里添加数据接收的处理逻辑
        if self.data_callback:
            try:
                self.data_callback(data)
            except Exception as e:
                logger.error(f"TCP数据回调处理失败: {e}")
                
                # 记录错误日志
                if self.system_logger:
                    self.system_logger.log_communication_event(
                        OperationType.COMMUNICATION_ERROR.value,
                        f"TCP数据回调处理失败: {str(e)}",
                        connection_info={"client_id": client_id, "type": "TCP"},
                        success=False
                    )
    
    def set_data_callback(self, callback: Callable):
        """设置数据回调函数"""
        self.data_callback = callback
    
    def start_communication(self):
        """启动通信"""
        try:
            if self.communication_type == "TCP" and self.tcp_client:
                # 启动TCP通信线程
                self.comm_thread = TCPCommunicationThread(self.tcp_client, self.data_callback, self)
                self.comm_thread.start()
                self.is_connected = True
                logger.info("TCP通信已启动")
                
                # 记录通信启动日志
                if self.system_logger:
                    self.system_logger.log_communication_event(
                        "启动通信",
                        "TCP通信已启动",
                        connection_info={"type": "TCP", "host": self.tcp_client.host, "port": self.tcp_client.port},
                        success=True
                    )
                return True
            elif self.serial_port:
                if self.serial_port.open():
                    # 启动串口通信线程
                    self.comm_thread = SerialCommunicationThread(self.serial_port, self.data_callback, self)
                    self.comm_thread.start()
                    self.is_connected = True
                    logger.info("串口通信已启动")
                    
                    # 记录通信启动日志
                    if self.system_logger:
                        self.system_logger.log_communication_event(
                            "启动通信",
                            "串口通信已启动",
                            connection_info={"type": "Serial", "port": self.serial_port.port, "baudrate": self.serial_port.baudrate},
                            success=True
                        )
                    return True
                else:
                    logger.error("串口打开失败")
                    
                    # 记录通信启动失败日志
                    if self.system_logger:
                        self.system_logger.log_communication_event(
                            "启动通信",
                            "串口打开失败",
                            connection_info={"type": "Serial", "port": self.serial_port.port},
                            success=False
                        )
                    return False
            return False
        except Exception as e:
            logger.error(f"启动通信失败: {e}")
            
            # 记录通信启动失败日志
            if self.system_logger:
                self.system_logger.log_communication_event(
                    "启动通信",
                    f"启动通信失败: {str(e)}",
                    connection_info={"type": self.communication_type},
                    success=False
                )
            return False
    
    def stop_communication(self):
        """停止通信"""
        try:
            if self.comm_thread:
                self.comm_thread.stop()
                self.comm_thread.wait()
                self.is_connected = False
                logger.info("通信已停止")
                
                # 记录通信停止日志
                if self.system_logger:
                    self.system_logger.log_communication_event(
                        "停止通信",
                        "通信已停止",
                        connection_info={"type": self.communication_type},
                        success=True
                    )
                return True
            return False
        except Exception as e:
            logger.error(f"停止通信失败: {e}")
            
            # 记录通信停止失败日志
            if self.system_logger:
                self.system_logger.log_communication_event(
                    "停止通信",
                    f"停止通信失败: {str(e)}",
                    connection_info={"type": self.communication_type},
                    success=False
                )
            return False
    
    def test_connection(self):
        """测试连接"""
        try:
            if self.communication_type == "TCP" and self.tcp_client:
                # 测试TCP连接
                return self.tcp_client.test_connection()
            elif self.serial_port:
                # 测试串口连接
                return self.serial_port.test_connection()
            return False
        except Exception as e:
            logger.error(f"测试连接失败: {e}")
            return False
    
    def get_connection_status(self):
        """获取连接状态"""
        return self.is_connected
    
    def get_communication_type(self):
        """获取通信类型"""
        return self.communication_type
    
    def send_data(self, data: bytes) -> bool:
        """发送数据"""
        try:
            if self.communication_type == "TCP" and self.tcp_client:
                return self.tcp_client.write(data)
            elif self.serial_port:
                return self.serial_port.write(data)
            return False
        except Exception as e:
            logger.error(f"发送数据失败: {e}")
            return False

class SerialCommunicationThread(QThread):
    """串口通信线程"""
    
    data_received = pyqtSignal(bytes)
    connection_status = pyqtSignal(bool)
    message_processed = pyqtSignal(dict)  # 添加处理后的消息信号
    
    def __init__(self, serial_port, data_callback=None, comm_manager=None):
        super().__init__()
        self.serial_port = serial_port
        self.data_callback = data_callback
        self.comm_manager = comm_manager
        self.running = False
        self.buffer = b''
        self.max_buffer_size = 1024 * 1024  # 1MB
        # 创建数据处理器
        self.data_processor = DataProcessor()
        
        # 获取系统日志管理器
        try:
            from src.utils.logger_manager import get_system_logger
            self.system_logger = get_system_logger()
        except ImportError:
            self.system_logger = None
    
    def run(self):
        """运行线程"""
        self.running = True
        logger.info("串口通信线程已启动")
        
        try:
            while self.running:
                if self.serial_port.is_open:  # 修改：is_open是属性，不是方法
                    # 读取串口数据
                    data = self.serial_port.read()
                    if data:
                        # 记录数据接收日志
                        if self.system_logger:
                            try:
                                data_size = len(data)
                                data_content = data.decode('utf-8', errors='ignore')[:100]
                                self.system_logger.log_data_reception(
                                    "串口数据",
                                    data_content,
                                    source=f"串口 {self.serial_port.port}",
                                    raw_data=data.hex()[:200],  # 限制原始数据长度
                                    details={
                                        "port": self.serial_port.port,
                                        "baudrate": self.serial_port.baudrate,
                                        "data_size": data_size,
                                        "protocol": "Serial"
                                    }
                                )
                            except Exception as e:
                                logger.error(f"记录串口数据接收日志失败: {e}")
                        
                        # 添加到缓冲区
                        self.buffer += data
                        
                        # 防止缓冲区过大
                        if len(self.buffer) > self.max_buffer_size:
                            logger.warning(f"串口缓冲区过大 ({len(self.buffer)} bytes)，清空缓冲区")
                            self.buffer = b''
                            continue
                        
                        # 处理缓冲区中的完整消息
                        self.process_buffer()
                        
                        # 发送原始数据信号
                        self.data_received.emit(data)
                        
                        # 调用回调函数
                        if self.data_callback:
                            try:
                                self.data_callback(data)
                            except Exception as e:
                                logger.error(f"串口数据回调函数执行失败: {e}")
                                
                                # 记录错误日志
                                if self.system_logger:
                                    self.system_logger.log_communication_event(
                                        "串口数据处理错误",
                                        f"串口数据回调函数执行失败: {str(e)}",
                                        connection_info={"port": self.serial_port.port, "type": "Serial"},
                                        success=False
                                    )
                
                self.msleep(50)  # 50ms间隔
                
        except Exception as e:
            logger.error(f"串口通信线程错误: {e}")
            
            # 记录错误日志
            if self.system_logger:
                self.system_logger.log_communication_event(
                    "串口通信错误",
                    f"串口通信线程错误: {str(e)}",
                    connection_info={"port": self.serial_port.port, "type": "Serial"},
                    success=False
                )
        finally:
            self.running = False
            logger.info("串口通信线程已停止")
    
    def process_buffer(self):
        """处理缓冲区中的完整消息"""
        processed_count = 0
        
        # 处理自定义LIS协议消息
        while b'<TRANSMIT>' in self.buffer and b'</TRANSMIT>' in self.buffer:
            start_idx = self.buffer.find(b'<TRANSMIT>')
            end_idx = self.buffer.find(b'</TRANSMIT>', start_idx)
            
            if end_idx == -1:
                # 没有找到结束标记，等待更多数据
                break
                
            # 提取完整消息
            message_end = end_idx + len(b'</TRANSMIT>')
            message_data = self.buffer[start_idx:message_end]
            
            # 处理消息 - 使用数据处理器而不是ProtocolProcessor
            try:
                message = self.data_processor.process_data(message_data)
                if message:
                    processed_count += 1
                    if self.comm_manager:
                        self.comm_manager.message_count += 1
                    
                    logger.info(f"串口收到第 {self.comm_manager.message_count if self.comm_manager else processed_count} 条 {message['protocol']} 协议消息")
                    
                    # 发送处理后的消息信号
                    self.message_processed.emit(message)
                    
                    # 注意：串口协议通常不需要ACK响应
                    # 如果需要ACK，可以在这里添加
                    
            except Exception as e:
                logger.error(f"串口消息处理失败: {e}")
            
            # 移除已处理的消息
            self.buffer = self.buffer[message_end:]
        
        if processed_count > 0:
            logger.info(f"串口本次处理了 {processed_count} 条消息，缓冲区剩余 {len(self.buffer)} 字节")
    
    def stop(self):
        """停止线程"""
        self.running = False

class DataProcessor:
    """数据处理器"""
    
    def __init__(self):
        self.parsers = {}
        self.register_parsers()
    
    def register_parsers(self):
        """注册协议解析器"""
        # 注册自定义LIS协议解析器（串口版本）
        try:
            # 尝试导入CustomLISParser
            if SERIAL_AVAILABLE:
                from src.protocols.serial.serial_protocol import CustomLISParser
                self.parsers['custom_lis'] = CustomLISParser()
                logger.info("自定义LIS协议解析器（串口）注册成功")
            else:
                logger.warning("串口模块不可用，自定义LIS协议解析器不可用")
        except Exception as e:
            logger.warning(f"自定义LIS协议解析器（串口）不可用: {e}")
        
        # 注册自定义LIS协议解析器（TCP版本）
        try:
            if TCP_AVAILABLE:
                from src.protocols.tcp.tcp_protocol import CustomLISParser as TCPCustomLISParser
                self.parsers['tcp_custom_lis'] = TCPCustomLISParser()
                logger.info("自定义LIS协议解析器（TCP）注册成功")
            else:
                logger.warning("TCP模块不可用，自定义LIS协议解析器不可用")
        except Exception as e:
            logger.warning(f"自定义LIS协议解析器（TCP）不可用: {e}")
        
        # 注册HL7协议解析器
        # self.parsers['hl7'] = HL7Parser()
    
    def process_data(self, data: bytes) -> dict:
        """处理接收到的数据"""
        try:
            # 检测协议类型
            protocol_type = self.detect_protocol(data)
            
            if protocol_type in self.parsers:
                return self.parsers[protocol_type].parse_message(data)
            else:
                logger.warning(f"未知协议类型: {protocol_type}")
                return {}
        except Exception as e:
            logger.error(f"数据处理失败: {e}")
            return {}
    
    def detect_protocol(self, data: bytes) -> str:
        """检测协议类型"""
        # 改进的协议检测逻辑
        if b'<TRANSMIT>' in data:
            # 检查是否为TCP协议（可以通过其他特征区分）
            # 这里暂时都使用custom_lis，后续可以根据具体特征区分
            return 'custom_lis'
        elif data.startswith(b'STX'):
            return 'custom_lis'
        elif data.startswith(b'MSH'):
            return 'hl7'
        else:
            return 'unknown'
    
    def create_sample_from_parsed_data(self, parsed_data: dict, raw_data: str = "", communication_type: str = "串口") -> 'Sample':
        """从解析的数据创建Sample对象"""
        try:
            from src.models.models import Sample, SampleInfo, Results, ImageInfo, ModeInfo
            import time
            import uuid
            
            # 生成唯一ID
            unique_id = str(uuid.uuid4())
            
            # 根据通信类型确定协议名称
            base_protocol = parsed_data.get('protocol', 'CUSTOM_LIS')
            if communication_type == "TCP":
                protocol = f"TCP_{base_protocol}"
            else:
                protocol = f"SERIAL_{base_protocol}"
            
            # 创建SampleInfo对象
            sample_info_data = parsed_data.get('sample_info', {})
            sample_info = SampleInfo(
                sample_id=sample_info_data.get('sample_id', ''),
                sample_number=sample_info_data.get('sample_no', '') or sample_info_data.get('sample_number', ''),
                patient_name=sample_info_data.get('patient_name', '未知患者'),
                patient_age=sample_info_data.get('patient_age', 0),
                patient_gender=sample_info_data.get('patient_gender', ''),
                datetime=sample_info_data.get('datetime', ''),
                sample_type=sample_info_data.get('sample_type', ''),
                sample_type_name=sample_info_data.get('sample_type_name', ''),
                sample_category=sample_info_data.get('sample_category', ''),
                report_id=sample_info_data.get('report_id', '') or sample_info_data.get('sample_id', '')
            )
            
            # 创建Results对象
            results_data = parsed_data.get('results', {})
            results = Results(
                HbA1a=str(results_data.get('HbA1a', '')),
                HbA1b=str(results_data.get('HbA1b', '')),
                HbF=str(results_data.get('HbF', '')),
                LA1c=str(results_data.get('LA1c', '')),
                HbA1c=str(results_data.get('HbA1c', '')),
                HbA0=str(results_data.get('HbA0', '')),
                eAG=str(results_data.get('eAG', '')),
                A2=str(results_data.get('A2', '')),
                HbE=str(results_data.get('HbE', '')),
                HbD=str(results_data.get('HbD', '')),
                HbS=str(results_data.get('HbS', '')),
                HbC=str(results_data.get('HbC', '')),
                p3=str(results_data.get('p3', '')),
                v_win=str(results_data.get('v-win', '')),
                TIME=results_data.get('TIME', []),
                AREA=results_data.get('AREA', []),
                TIME_DETAILS=results_data.get('TIME_DETAILS', {}),
                AREA_DETAILS=results_data.get('AREA_DETAILS', {}),
                other_results=results_data.get('other_results', {})
            )
            
            # 创建ImageInfo对象
            image_data = parsed_data.get('image', {})
            # logger.debug(f"处理图片数据: {image_data}")
            
            # 处理图片数据，支持多种字段名
            hex_data = image_data.get('hex_data', '') or image_data.get('data', '')
            base64_data = image_data.get('base64_data', '')
            
            image = ImageInfo(
                filename=image_data.get('filename', ''),
                size=image_data.get('size', 0),
                path=image_data.get('path', ''),
                saved=image_data.get('saved', False),
                hex_data=hex_data,
                base64_data=base64_data,
                error=image_data.get('error', '')
            )
            
            # 创建ModeInfo对象
            mode_info_data = parsed_data.get('mode_info', {})
            mode_info = ModeInfo(
                mode_name=mode_info_data.get('name', ''),
                mode_description=mode_info_data.get('description', ''),
                test_count=mode_info_data.get('test_count', 0),
                test_items=mode_info_data.get('test_items', [])
            )
            
            # 处理接收时间
            receive_time = datetime.now()
            if sample_info.datetime:
                try:
                    # 尝试解析时间格式
                    time_formats = [
                        "%Y-%m-%d-%H-%M",  # 2025-07-31-14-19
                        "%Y-%m-%d %H:%M:%S",  # 2025-07-31 14:19:30
                        "%Y-%m-%d %H:%M",  # 2025-07-31 14:19
                        "%Y/%m/%d %H:%M:%S",  # 2025/07/31 14:19:30
                    ]
                    
                    for fmt in time_formats:
                        try:
                            receive_time = datetime.strptime(sample_info.datetime, fmt)
                            break
                        except ValueError:
                            continue
                except Exception as e:
                    logger.warning(f"时间解析失败: {sample_info.datetime}, 使用当前时间")
            
            # 创建Sample对象
            sample = Sample(
                id=unique_id,
                protocol=protocol,  # 使用根据通信类型确定的协议名称
                machine_model=parsed_data.get('machine_model', ''),
                machine_id=parsed_data.get('machine_id', ''),
                sample_info=sample_info,
                results=results,
                image=image,
                analysis_mode=parsed_data.get('analysis_mode', ''),
                mode_info=mode_info,
                raw=raw_data,
                receive_time=receive_time
            )
            
            logger.info(f"成功创建Sample对象: {sample.id}, 协议: {protocol}, 通信类型: {communication_type}")
            return sample
            
        except Exception as e:
            logger.error(f"创建Sample对象失败: {e}")
            import traceback
            logger.error(f"详细错误信息: {traceback.format_exc()}")
            raise
    
    def extract_sample_info(self, parsed_data: dict, communication_type: str = "串口") -> dict:
        """提取样本信息 - 保持向后兼容"""
        try:
            # 根据通信类型确定协议名称
            base_protocol = parsed_data.get('protocol', 'CUSTOM_LIS')
            if communication_type == "TCP":
                protocol = f"TCP_{base_protocol}"
            else:
                protocol = f"SERIAL_{base_protocol}"
            
            # 基础信息提取
            sample_info = {
                'instrument_id': parsed_data.get('machine_id', ''),
                'instrument_model': parsed_data.get('machine_model', ''),
                'instrument_number': parsed_data.get('machine_id', ''),
                'protocol_type': protocol,  # 使用根据通信类型确定的协议名称
                'sample_number': '',
                'sample_id': '',
                'instrument_type': parsed_data.get('machine_model', ''),
                'analysis_time': '',
                'test_results': '',
                'test_image_path': '',
                'report_id': '',
                'patient_name': '未知患者',
                'patient_age': 0,
                'patient_gender': ''
            }
            
            # 提取样本信息
            sample_data = parsed_data.get('sample_info', {})
            if sample_data:
                sample_info['sample_number'] = sample_data.get('sample_no', '') or sample_data.get('sample_number', '')
                sample_info['sample_id'] = sample_data.get('sample_id', '') or sample_data.get('sample_no', '')
                sample_info['report_id'] = sample_data.get('sample_id', '') or sample_data.get('sample_no', '')
                
                # 处理分析时间
                datetime_str = sample_data.get('datetime', '')
                if datetime_str:
                    try:
                        # 尝试解析时间格式
                        # 支持多种时间格式
                        time_formats = [
                            "%Y-%m-%d-%H-%M",  # 2025-07-31-14-19
                            "%Y-%m-%d %H:%M:%S",  # 2025-07-31 14:19:30
                            "%Y-%m-%d %H:%M",  # 2025-07-31 14:19
                            "%Y/%m/%d %H:%M:%S",  # 2025/07/31 14:19:30
                        ]
                        
                        parsed_time = None
                        for fmt in time_formats:
                            try:
                                parsed_time = datetime.strptime(datetime_str, fmt)
                                break
                            except ValueError:
                                continue
                        
                        if parsed_time:
                            sample_info['analysis_time'] = parsed_time.strftime("%Y-%m-%d %H:%M:%S")
                        else:
                            sample_info['analysis_time'] = datetime_str
                    except Exception as e:
                        logger.warning(f"时间解析失败: {datetime_str}, 错误: {e}")
                        sample_info['analysis_time'] = datetime_str
            
            # 提取检测结果
            results_data = parsed_data.get('results', {})
            if results_data:
                # 格式化检测结果
                formatted_results = []
                
                # 处理基础检测项目
                basic_items = ['HbA1a', 'HbA1b', 'HbF', 'LA1c', 'HbA1c', 'HbA0', 'eAG']  # 修正字段名
                for item in basic_items:
                    if item in results_data:
                        value = results_data[item]
                        formatted_results.append(f"{item}: {value}")
                
                # 处理变异筛查项目
                variant_items = ['A2', 'HbE', 'HbD', 'HbS', 'HbC', 'p3', 'v-win']
                for item in variant_items:
                    if item in results_data:
                        value = results_data[item]
                        formatted_results.append(f"{item}: {value}")
                
                # 处理TIME数据
                if 'TIME_DETAILS' in results_data:
                    time_details = results_data['TIME_DETAILS']
                    formatted_results.append("出峰时间:")
                    for time_item, time_value in time_details.items():
                        formatted_results.append(f"  {time_item}: {time_value}秒")
                
                # 处理AREA数据
                if 'AREA_DETAILS' in results_data:
                    area_details = results_data['AREA_DETAILS']
                    formatted_results.append("面积数据:")
                    for area_item, area_value in area_details.items():
                        formatted_results.append(f"  {area_item}: {area_value}")
                
                # 处理分析模式信息
                mode_info = parsed_data.get('mode_info', {})
                if mode_info:
                    formatted_results.append(f"分析模式: {mode_info.get('name', '未知')}")
                    formatted_results.append(f"模式描述: {mode_info.get('description', '')}")
                
                sample_info['test_results'] = '\n'.join(formatted_results)
            
            # 提取图片信息
            image_data = parsed_data.get('image', {})
            if image_data:
                sample_info['test_image_path'] = image_data.get('path', '')
                
                # 如果图片保存成功，记录图片信息
                if image_data.get('saved', False):
                    sample_info['test_image_path'] = image_data.get('path', '')
                    logger.info(f"图片已保存: {sample_info['test_image_path']}")
                else:
                    logger.warning(f"图片保存失败: {image_data.get('error', '未知错误')}")
            
            # 生成样本编号（如果没有的话）
            if not sample_info['sample_number']:
                import time
                timestamp = int(time.time())
                sample_info['sample_number'] = f"SAMPLE_{timestamp}"
                sample_info['sample_id'] = f"SAMPLE_{timestamp}"
                sample_info['report_id'] = f"SAMPLE_{timestamp}"
            
            # 记录接收时间
            if not sample_info['analysis_time']:
                sample_info['analysis_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            
            logger.info(f"提取的样本信息: {sample_info}")
            return sample_info
            
        except Exception as e:
            logger.error(f"提取样本信息失败: {e}")
            import traceback
            logger.error(f"详细错误信息: {traceback.format_exc()}")
            
            # 返回基础信息
            return {
                'instrument_id': parsed_data.get('machine_id', ''),
                'instrument_model': parsed_data.get('machine_model', ''),
                'instrument_number': parsed_data.get('machine_id', ''),
                'protocol_type': parsed_data.get('protocol', 'CUSTOM_LIS'),
                'sample_number': f"ERROR_{int(time.time())}",
                'sample_id': f"ERROR_{int(time.time())}",
                'instrument_type': parsed_data.get('machine_model', ''),
                'analysis_time': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'test_results': f"数据解析错误: {str(e)}",
                'test_image_path': '',
                'report_id': f"ERROR_{int(time.time())}",
                'patient_name': '未知患者',
                'patient_age': 0,
                'patient_gender': ''
            } 

    def stop_all(self):
        """停止所有通信和数据处理"""
        try:
            # 停止通信
            self.stop_communication()
            
            # 停止TCP服务器
            self.stop_tcp_server()
            
            # 停止数据处理线程
            self._stop_data_processing_thread()
            
            logger.info("所有通信和数据处理已停止")
            return True
        except Exception as e:
            logger.error(f"停止所有通信和数据处理失败: {e}")
            return False
    
    def __del__(self):
        """析构函数，确保线程正确停止"""
        try:
            self._stop_data_processing_thread()
        except:
            pass 